import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:intl/intl.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';

class AddMainsElectricityPriceController extends GetxController {
  bool isEnableCommit = false;
  late int siteId;
  List<String> titleStringList = [
    ResKey.basicInfo.tr,
    ResKey.basicEleFee.tr,
    ResKey.siteSettingElectricityStagePrice.tr,
    ResKey.siteSettingEffectiveDate.tr,
    ResKey.siteSettingElectricityStagePrice.tr
  ];
  List<String> titleDetailList = [
    ResKey.siteSettingElectricityRoleName.tr,
    ResKey.siteSettingElectricityPowerFactor.tr,
    ResKey.siteSettingElectricityMaxNeed.tr,
    ResKey.siteSettingElectricityNeedCapacityBill.tr,
    ResKey.siteSettingElectricityShapePrice.tr,
    ResKey.siteSettingElectricityPeakPrice.tr,
    ResKey.siteSettingElectricityAveragePrice.tr,
    ResKey.siteSettingElectricityValleyPrice.tr
  ];
  List<String> unitList = [
    '',
    '',
    'kW',
    ResKey.yuan.tr,
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh'
  ];
  List<dynamic> timeDateList = [
    {
      'effectiveTime': '01-01',
      'expirationTime': '12-31',
    }
  ];
  List<dynamic> peakAndPlateauList = [
    {'intervalStartTime': '00:00', 'intervalEndTime': '24:00', 'type': 0}
  ];

  int status = 1;
  int electricityType = -1;
  final DeviceServices services = Get.put(DeviceServices());
  final TextEditingController ruleNameController = TextEditingController();
  final TextEditingController powerElementController = TextEditingController();
  final TextEditingController maxCapacityController = TextEditingController();
  final TextEditingController needPriceController = TextEditingController();

  final TextEditingController maxPriceController = TextEditingController();
  final TextEditingController peakPriceController = TextEditingController();
  final TextEditingController averageProtectController =
      TextEditingController();
  final TextEditingController valleyReleaseController = TextEditingController();
  @override
  void onInit() {
    super.onInit();
    siteId = Get.arguments;
    GetStorage storage = GetStorage();
    String unit = storage.read('monetaryUnitName')??'元';
    if(unit == '元' || unit == '¥'){
      unit = ResKey.yuan.tr;
    }
    unitList = [
      '',
      '',
      'kW',
      unit,
      '${unit}/kWh',
      '${unit}/kWh',
      '${unit}/kWh',
      '${unit}/kWh'
    ];
  }

  @override
  void onReady() {}

  @override
  void onClose() {}
  Future<void> save() async {
    var param = {
      "name": ruleNameController.text,
      "status": status,
      "siteId": siteId,
      // "powerFactor": powerElementController.text,
      "electricityType": electricityType,
      // "maxDemand": maxCapacityController.text,
      // "demandElectrovalency": needPriceController.text,
    };
    if (timeDateList.isNotEmpty) {
      param['effectiveTimeList'] = timeDateList;
    }

    if (peakAndPlateauList.isNotEmpty) {
      param['hoursPriceList'] = peakAndPlateauList;
    }
    if (powerElementController.text.isNotEmpty) {
      param['powerFactor'] = powerElementController.text;
    }
    if (maxCapacityController.text.isNotEmpty) {
      param['maxDemand'] = maxCapacityController.text;
    }
    if (needPriceController.text.isNotEmpty) {
      param['demandElectrovalency'] = needPriceController.text;
    }

    if (maxPriceController.text.isNotEmpty) {
      param['sharpPrice'] = maxPriceController.text;
    }
    if (valleyReleaseController.text.isNotEmpty) {
      param['valleyPrice'] = valleyReleaseController.text;
    }
    if (averageProtectController.text.isNotEmpty) {
      param['flatPrice'] = averageProtectController.text;
    }
    if (peakPriceController.text.isNotEmpty) {
      param['peakPrice'] = peakPriceController.text;
    }
    showLoading(toast: ResKey.loading.tr);
    var result = await services.siteMainsAdd(
      param,
      onError: (p0) {
        dismissLoading();
        handleException(p0);

        return false;
      },
    );
    dismissLoading();
    Log.d('result==' + result.toString());
    if (result == true) {
      Get.back(result: true);
    }
  }

  ///下一步按钮是否可以点击
  checkCommitStatus() {
    if (ruleNameController.text.isNotEmpty && timeDateList.isNotEmpty && peakAndPlateauList.isNotEmpty){
      isEnableCommit = true;
    } else {
      isEnableCommit = false;
    }
    Log.d('isEnableCommit==' + isEnableCommit.toString());
    update();
  }

  void cancelEdit() {
    Get.back();
  }

  void updateTimeList() {
    timeDateList.addAll([
      {
        'effectiveTime': '01-01',
        'expirationTime': '12-31',
      }
    ]);
    checkCommitStatus();
    update();
  }

  void deleteTimeList(int index) {
    timeDateList.removeAt(index);
    checkCommitStatus();
    update();
  }

  void updatePeakAndPlateauListList() {
    peakAndPlateauList.addAll([
      {"intervalStartTime": "00:00", "intervalEndTime": "24:00", 'type': 0}
    ]);
    checkCommitStatus();
    update();
  }

  void deletePeakAndPlateauListList(int index) {
    peakAndPlateauList.removeAt(index);
    checkCommitStatus();
    update();
  }

  String handleTimeToHour(DateTime? time) {
    Log.d('DateTime==' + time.toString());
    if (time != null) {
      String str = time.toString();
      if (time.toString().length > 16) {
        String timeString = '${str.substring(11, 13)}:${str.substring(14, 16)}';
        if (timeString == '24:00') {
          timeString = '24:00';
        }
        Log.d('timeString==' + timeString.toString());
        return timeString;
      }
    }

    return '';
  }

  String handleTimeToMonth(DateTime? time) {
    Log.d('DateTime==' + time.toString());
    if (time != null) {
      String str = time.toString();
      if (time.toString().length > 16) {
        return '${str.substring(5, 7)}-${str.substring(8, 10)}';
      }
    }

    return '';
  }

  ///初始化开始时间从零点开始
  DateTime initStartTime() {
    var now = DateTime.now(); //当前时间
    DateTime date = DateTime(now.year, now.month, now.day, 00, 00);
    Log.d('date2==' + date.toString());
    return date;
  }

  ///初始化开始时间23:59结束
  DateTime initEndTime() {
    var now = DateTime.now(); //当前时间
    DateTime date = DateTime(now.year, now.month, now.day, 23, 59);
    Log.d('date2==' + date.toString());
    return date;
  }
}
